package com.hb.config;

import com.hb.service.SpitterService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;

import java.util.Properties;

@Configuration
public class SpringInvokerConfig {
    /**
     * 为了把 Spitter 服务导出为一个基于 HTTP invoker 的服务，我们需要像下面的配置一样声明一个 HttpInvokerServiceExporter bean
     *
     * @param service
     * @return
     */
    @Bean
    public HttpInvokerServiceExporter httpExportedSpitterService(SpitterService service) {
        HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
        exporter.setService(service);
        exporter.setServiceInterface(SpitterService.class);
        return exporter;
    }

    /**
     * 因为 HttpInvokerServiceExporter 是一个 Spring MVC 控制器，我们需要建立一个 URL 处理器，映射 HTTP URL 到对应的服务上，就像 Hessian 和 Burlap 导出器所做的一样。
     *
     * @return
     */
    @Bean
    public HandlerMapping httpInvokerMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        Properties mappings = new Properties();
        mappings.setProperty("/spitter.service", "httpExportedSpitterService");
        mapping.setMappings(mappings);
        return mapping;
    }

    /**
     * 为了把基于 HTTP invoker 的远程服务装配进我们的客户端 Spring 应用上下文中，我们必须将 HttpInvokerProxyFactoryBean 配置为一个 bean 来代理它
     * @return
     */
    @Bean
    public HttpInvokerProxyFactoryBean spitterService() {
        HttpInvokerProxyFactoryBean proxy = new HttpInvokerProxyFactoryBean();
        proxy.setServiceUrl("http://localhost:8080/Spitter/spitter.service");
        proxy.setServiceInterface(SpitterService.class);
        return proxy;
    }
}
